// 引入axios
import axios from 'axios';

// 引入 ElMessage
import { ElMessage } from 'element-plus';

let baseUrl = "http://localhost:8000/";
// 创建axios实例
const httpService = axios.create({
    // url前缀-'http:xxx.xxx'
    // baseURL: process.env.BASE_API, // 需自定义
    baseURL: baseUrl,
    // 请求超时时间
    timeout: 30000 // 需自定义
});

//添加请求和响应拦截器
// 添加请求拦截器
httpService.interceptors.request.use(function (config) {
    // 从 sessionStorage 中获取 token
    const token = window.sessionStorage.getItem('token')
    if (token) {
        // 添加 Bearer 前缀
        config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
});

// 当前是否正在刷新token
let isRefreshing = false
// 存储等待刷新token的请求
let requests = []

// 刷新token的函数
function refreshToken() {
    return new Promise((resolve, reject) => {
        const refreshToken = window.sessionStorage.getItem('refresh')
        if (!refreshToken) {
            reject(new Error('没有刷新令牌'))
            return
        }

        // 创建一个新的axios实例来发送刷新请求，避免循环依赖
        axios({
            url: baseUrl + 'api/token/refresh/',
            method: 'post',
            data: { refresh: refreshToken },
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(response => {
            // 更新token
            window.sessionStorage.setItem('token', response.data.access)
            window.sessionStorage.setItem('refresh', response.data.refresh)
            resolve(response.data.access)
        }).catch(error => {
            // 刷新失败，需要重新登录
            console.error('刷新令牌失败:', error)
            reject(error)
        })
    })
}

// 添加响应拦截器
httpService.interceptors.response.use(
    response => {
        // 2xx 范围内的状态码都会触发该函数
        return response.data
    },
    async error => {
        // 超出 2xx 范围的状态码都会触发该函数
        if (error.response) {
            // 服务器返回了错误状态码
            const status = error.response.status
            const data = error.response.data
            const config = error.config

            // 处理 401 未授权错误（通常是token过期或无效）
            if (status === 401 && !config.url.includes('/login')) {
                // 如果不是刷新token的请求，尝试刷新token
                if (!config.url.includes('/api/token/refresh/')) {
                    if (!isRefreshing) {
                        isRefreshing = true

                        try {
                            // 刷新token
                            const newToken = await refreshToken()

                            // 重新发送所有等待的请求
                            requests.forEach(cb => cb(newToken))
                            requests = []

                            // 重新发送当前请求
                            config.headers['Authorization'] = `Bearer ${newToken}`
                            return httpService(config)
                        } catch (err) {
                            // 刷新token失败，需要重新登录
                            ElMessage.error('登录已过期，请重新登录')
                            // 清除所有会话数据
                            window.sessionStorage.removeItem('token')
                            window.sessionStorage.removeItem('refresh')
                            window.sessionStorage.removeItem('menuList')
                            window.sessionStorage.removeItem('permissions')
                            window.sessionStorage.removeItem('currentUser')
                            localStorage.clear()
                            sessionStorage.clear()
                            // 跳转到登录页
                            window.location.href = '/login'
                            return Promise.reject(new Error('登录已过期'))
                        } finally {
                            isRefreshing = false
                        }
                    } else {
                        // 当前正在刷新token，将请求添加到等待队列
                        return new Promise((resolve) => {
                            requests.push((token) => {
                                config.headers['Authorization'] = `Bearer ${token}`
                                resolve(httpService(config))
                            })
                        })
                    }
                } else {
                    // 刷新token的请求也失败，需要重新登录
                    ElMessage.error('登录已过期，请重新登录')
                    // 清除所有会话数据
                    window.sessionStorage.removeItem('token')
                    window.sessionStorage.removeItem('refresh')
                    window.sessionStorage.removeItem('menuList')
                    window.sessionStorage.removeItem('permissions')
                    window.sessionStorage.removeItem('currentUser')
                    // 跳转到登录页
                    window.location.href = '/login'
                    return Promise.reject(new Error('登录已过期'))
                }
            }

            ElMessage.error(data.msg || '请求失败')
            return Promise.reject(data)
        } else if (error.request) {
            // 请求已经发出，但没有收到响应
            ElMessage.error('网络错误，请检查网络连接')
            return Promise.reject(error)
        } else {
            // 请求配置发生的错误
            ElMessage.error('请求配置错误')
            return Promise.reject(error)
        }
    }
)

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params
        }).then(response => {
            console.log(response)
            resolve(response);
        }).catch(error => {
            console.log(error)
            reject(error);
        });
    });
}

export function put(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'put',
            data: params
        }).then(response => {
            // console.log(response)
            resolve(response);
        }).catch(error => {
            console.log(error)
            reject(error);
        });
    });
}

export function patch(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'patch',
            data: params
        }).then(response => {
            console.log(response)
            resolve(response);
        }).catch(error => {
            console.log(error)
            reject(error);
        });
    });
}

/*
 *  delete请求(delete是保留字，不能当做函数名)
 *  url:请求地址
 *  params:参数
 * */
export function del(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'delete',
            data: params
        }).then(response => {
            console.log(response)
            resolve(response);
        }).catch(error => {
            console.log(error)
            reject(error);
        });
    });
}


/*
 *  文件上传
 *  url:请求地址
 *  params:参数
 * */
export function fileUpload(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function getServerUrl() {
    return baseUrl;
}

export default {
    get,
    post,
    del,
    fileUpload,
    getServerUrl,
    patch,
    put
}
